package com.payment.transactions.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.payment.transactions.model.PaymentTransaction;
import com.payment.transactions.service.FileImportService;
import com.payment.transactions.service.PaymentTransactionService;

import cn.hutool.core.map.MapUtil;

@RestController
@RequestMapping("/api/transactions")
public class PaymentTransactionController {

    @Autowired
    private PaymentTransactionService transactionService;

    /**
     * 创建交易记录
     */
    @PostMapping
    public ResponseEntity<PaymentTransaction> createTransaction(@RequestBody PaymentTransaction transaction) {
        PaymentTransaction savedTransaction = transactionService.save(transaction);
        return new ResponseEntity<>(savedTransaction, HttpStatus.CREATED);
    }

    /**
     * 批量创建交易记录
     */
    @PostMapping("/batch")
    public ResponseEntity<?> createBatchTransactions(@RequestBody List<PaymentTransaction> transactions) {
        int savedCount = transactionService.saveAll(transactions);
        Map<String, Object> response = new HashMap<>();
        response.put("message", "批量新增成功");
        response.put("savedCount", savedCount);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID查询交易记录
     */
    @GetMapping("/{id}")
    public ResponseEntity<PaymentTransaction> getTransactionById(@PathVariable Integer id) {
        Optional<PaymentTransaction> transaction = transactionService.findById(id);
        return transaction.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 查询所有交易记录（分页）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllTransactions(@RequestParam Map<String, Object> params) {
        // 参数验证和范围限制
        Integer page = MapUtil.getInt(params, "page", 1);
        Integer size = MapUtil.getInt(params, "size", 50);
        if (page < 1)
            page = 1;
        if (size < 1)
            size = 50;

        Map<String, Object> result = transactionService.findAll(page, size, params);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 根据支付平台查询交易记录
     */
    @GetMapping("/platform/{platform}")
    public ResponseEntity<List<PaymentTransaction>> getTransactionsByPlatform(@PathVariable Integer platform) {
        List<PaymentTransaction> transactions = transactionService.findByPaymentPlatform(platform);
        return ResponseEntity.ok(transactions);
    }

    /**
     * 根据收支类型查询交易记录
     */
    @GetMapping("/income-expense/{type}")
    public ResponseEntity<List<PaymentTransaction>> getTransactionsByIncomeExpense(@PathVariable Integer type) {
        List<PaymentTransaction> transactions = transactionService.findByIncomeExpense(type);
        return ResponseEntity.ok(transactions);
    }

    /**
     * 根据交易状态查询交易记录
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<List<PaymentTransaction>> getTransactionsByStatus(@PathVariable String status) {
        List<PaymentTransaction> transactions = transactionService.findByTransactionStatus(status);
        return new ResponseEntity<>(transactions, HttpStatus.OK);
    }

    /**
     * 根据交易订单号查询交易记录
     */
    @GetMapping("/order-number/{orderNumber}")
    public ResponseEntity<PaymentTransaction> getTransactionByOrderNumber(@PathVariable String orderNumber) {
        Optional<PaymentTransaction> transaction = transactionService.findByTransactionOrderNumber(orderNumber);
        return transaction.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 根据商家订单号查询交易记录
     */
    @GetMapping("/merchant-order/{merchantOrderNumber}")
    public ResponseEntity<List<PaymentTransaction>> getTransactionsByMerchantOrderNumber(
            @PathVariable String merchantOrderNumber) {
        List<PaymentTransaction> transactions = transactionService.findByMerchantOrderNumber(merchantOrderNumber);
        return new ResponseEntity<>(transactions, HttpStatus.OK);
    }

    /**
     * 根据条件查询交易记录
     */
    @PostMapping("/search")
    public ResponseEntity<List<PaymentTransaction>> searchTransactions(@RequestBody Map<String, Object> searchParams) {
        List<PaymentTransaction> transactions = transactionService.findByCondition(searchParams);
        return new ResponseEntity<>(transactions, HttpStatus.OK);
    }

    /**
     * 更新交易记录
     */
    @PutMapping("/{id}")
    public ResponseEntity<PaymentTransaction> updateTransaction(@PathVariable Integer id,
            @RequestBody PaymentTransaction transaction) {
        Optional<PaymentTransaction> existingTransaction = transactionService.findById(id);
        if (existingTransaction.isPresent()) {
            transaction.setId(id);
            PaymentTransaction updatedTransaction = transactionService.update(transaction);
            return new ResponseEntity<>(updatedTransaction, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 删除交易记录（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTransaction(@PathVariable Integer id) {
        try {
            int result = transactionService.deleteById(id);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除成功");
            response.put("deletedCount", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 批量删除交易记录
     */
    @DeleteMapping("/batch")
    public ResponseEntity<?> deleteBatchTransactions(@RequestBody List<Integer> ids) {
        try {
            int result = transactionService.deleteAllById(ids);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "批量删除成功");
            response.put("deletedCount", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "批量删除失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 统计查询 - 按支付平台统计
     */
    @GetMapping("/stats/platform")
    public ResponseEntity<?> countByPlatform(@RequestParam(required = false) Map<String, Object> params) {
        try {
            List<Map<String, Object>> result = transactionService.countByPlatform(params);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "统计查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 将支付平台字符串转换为整数
     */
    private Integer convertPlatformToInteger(String platform) {
        if ("Alipay".equals(platform)) {
            return 1; // 假设1代表支付宝
        } else if ("WeChat".equals(platform)) {
            return 2; // 假设2代表微信
        }
        return null;
    }

    /**
     * 统计查询 - 按收支类型统计
     */
    @GetMapping("/stats/income-expense")
    public ResponseEntity<?> countByIncomeExpense(@RequestParam(required = false) Map<String, Object> params) {
        try {
            List<Map<String, Object>> result = transactionService.countByIncomeExpense(params);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "统计查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    /**
     * 统计查询 - 按交易对象统计
     */
    @GetMapping("/stats/transaction-partner")
    public ResponseEntity<?> countByTransactionPartner(@RequestParam(required = false) Map<String, Object> params) {
        try {
            List<Map<String, Object>> result = transactionService.countByTransactionPartner(params);
            Map<String, Object> response = new HashMap<>();
            response.put("message", "统计查询成功");
            response.put("data", result);
            response.put("code", HttpStatus.OK.value());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "统计查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @Autowired
    private FileImportService fileImportService;

    /**
     * 上传文件（支持多文件上传，Excel或CSV文件解析）
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("files") MultipartFile[] files) {
        Map<String, Object> result = new HashMap<>();
        List<String> successFiles = new ArrayList<>();
        List<String> errorFiles = new ArrayList<>();
        int totalRecords = 0;
        int totalSavedCount = 0;

        try {
            // 检查文件数组是否为空
            if (files == null || files.length == 0) {
                result.put("error", "上传文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 处理每个文件
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                try {
                    // 检查单个文件是否为空
                    if (file.isEmpty() || fileName == null) {
                        errorFiles.add("空文件");
                        continue;
                    }

                    // 检查文件大小（限制为10MB）
                    if (file.getSize() > 10 * 1024 * 1024) {
                        errorFiles.add(fileName + ": 文件大小超过10MB");
                        continue;
                    }

                    // 检查文件格式
                    if (!fileName.matches(".*\\.(xlsx|xls|csv)$")) {
                        errorFiles.add(fileName + ": 不支持的文件格式，只支持xlsx、xls和csv");
                        continue;
                    }

                    // 解析文件
                    List<PaymentTransaction> transactions = fileImportService.parseFile(file);

                    // 验证解析结果
                    if (transactions.isEmpty()) {
                        errorFiles.add(fileName + ": 文件中没有找到有效的数据");
                        continue;
                    }

                    // 检查交易单号和平台重复
                    List<PaymentTransaction> validTransactions = new ArrayList<>();
                    List<String> duplicateRecords = new ArrayList<>();
                    
                    for (PaymentTransaction transaction : transactions) {
                        // 根据交易订单号查询现有记录
                        Optional<PaymentTransaction> existingTransaction = transactionService.findByTransactionOrderNumber(
                                transaction.getTransactionOrderNumber());
                        
                        // 检查是否存在相同支付平台和交易单号的记录
                        if (existingTransaction.isPresent() && 
                                existingTransaction.get().getPaymentPlatform().equals(transaction.getPaymentPlatform())) {
                            // 记录重复信息
                            duplicateRecords.add("交易单号: " + transaction.getTransactionOrderNumber() + 
                                    ", 平台: " + (transaction.getPaymentPlatform() == 1 ? "微信" : "支付宝") + 
                                    ", 交易对方: " + transaction.getTransactionPartner() + 
                                    ", 金额: " + transaction.getAmount());
                        } else {
                            // 添加到有效记录列表
                            validTransactions.add(transaction);
                        }
                    }

                    // 处理检查结果
                    if (!duplicateRecords.isEmpty()) {
                        // 有重复记录，记录信息但仍然保存非重复数据
                        String warningMsg = fileName + ": 发现" + duplicateRecords.size() + "条重复记录，这些记录将被跳过，其余记录将继续保存。";
                        
                        // 将重复记录详情添加到结果中
                        if (!result.containsKey("duplicateRecords")) {
                            result.put("duplicateRecords", new HashMap<>());
                        }
                        ((Map<String, Object>) result.get("duplicateRecords")).put(fileName, duplicateRecords);
                    }
                    
                    // 无论是否有重复记录，只要有有效记录就保存
                    if (!validTransactions.isEmpty()) {
                        // 保存非重复的有效数据
                        int savedCount = transactionService.saveAll(validTransactions);
                        successFiles.add(fileName);
                        totalRecords += transactions.size();
                        totalSavedCount += savedCount;
                    } else {
                        errorFiles.add(fileName + ": 没有可保存的有效数据");
                    }

                } catch (IllegalArgumentException e) {
                    errorFiles.add(fileName + ": 参数错误 - " + e.getMessage());
                } catch (ParseException e) {
                    errorFiles.add(fileName + ": 日期解析错误 - " + e.getMessage());
                } catch (Exception e) {
                    errorFiles.add(fileName + ": 处理失败 - " + e.getMessage());
                }
            }

            // 根据处理结果返回响应
            if (successFiles.isEmpty()) {
                result.put("error", "所有文件处理失败");
                result.put("errorFiles", errorFiles);
                return ResponseEntity.badRequest().body(result);
            }

            // 返回成功结果
            result.put("message", "文件上传并导入成功");
            result.put("successFiles", successFiles);
            result.put("errorFiles", errorFiles);
            result.put("totalFiles", files.length);
            result.put("successCount", successFiles.size());
            result.put("errorCount", errorFiles.size());
            result.put("totalRecords", totalRecords);
            result.put("totalSavedCount", totalSavedCount);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            result.put("error", "处理请求失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}